
#include <QDebug>

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), completer(new QCompleter(this)), completer_model(new QStandardItemModel(this)), dpkg(new Dpkg(this))
{
    ui->setupUi(this);

    completer_model->setColumnCount(1);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    completer->setFilterMode(Qt::MatchContains);
    completer->setCompletionMode(QCompleter::PopupCompletion);
    completer->setModel(completer_model.data());
    ui->lineEdit_Package->setCompleter(completer.data());

    connect(ui->pushButton_Refresh, &QPushButton::clicked, this, &MainWindow::On_Refresh_Clicked);
    connect(ui->pushButton_ShowInfo, &QPushButton::clicked, this, &MainWindow::On_ShowInfo_Clicked);
    connect(ui->lineEdit_Package, &QLineEdit::editingFinished, this, &MainWindow::On_Package_EditingFinished);

    connect(dpkg.data(), &Dpkg::Updated, this, &MainWindow::On_DPKG_Updated);

    dpkg->LoadStatus();
}

MainWindow::~MainWindow()
{
    delete ui;
    completer_model->clear();
}

void MainWindow::On_Refresh_Clicked()
{
    dpkg->LoadStatus();
}

void MainWindow::On_ShowInfo_Clicked()
{
    QString package = ui->lineEdit_Package->text();
    if (package.isEmpty()) {
        return;
    }
    const PKGInfo &info = dpkg->GetPackageInfo(package);
    ui->label_info_package->setText(info.name);
    ui->label_info_version->setText(info.version.toString());
    ui->label_info_architecture->setText(info.arch.name);
    ui->label_info_depends->setText(info.depends());
    ui->label_info_section->setText(info.section);
    ui->label_info_priority->setText(info.ConvPriority(info.priority));
    ui->label_info_status->setText(info.ConvStatus(info.status));
    ui->label_info_summary->setText(info.summary);
    ui->label_info_description->setText(info.description);
}

void MainWindow::On_Package_EditingFinished()
{
    On_ShowInfo_Clicked();
}

void MainWindow::On_DPKG_Updated()
{
    QString status = QString::asprintf("Packages: %d availables, %d installed.", dpkg->available().count(), dpkg->installed().count());
    ui->label_packages_status->setText(status);

    completer_model->clear();
    for (const PKGInfo &info : qAsConst(dpkg->installed())) {
        completer_model->appendRow(new QStandardItem(info.name));
    }
    for (const PKGInfo &info : qAsConst(dpkg->available())) {
        completer_model->appendRow(new QStandardItem(info.name));
    }
}
